/*
* 工装夹具类型管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 获取所有工装夹具类型列表
router.get("/list", async (req, res) => {
    console.log("===========获取工装夹具类型列表接口============");
    // 获取参数
    let { pageNum, pageSize, toolTypeCode, toolTypeName, maintenType } = req.query;
    // 拼接sql语句
    let sql = "select * from tm_tool_type";
    let sql_where = ` where 1=1`;
    if(toolTypeCode){
        sql_where += ` and tool_type_code like '%${toolTypeCode}%'`;
    }
    if(toolTypeName){
        sql_where += ` and tool_type_name like '%${toolTypeName}%'`;
    }
    if(maintenType){
        sql_where += ` and mainten_type = '${maintenType}'`;
    }
    if(toolTypeCode || toolTypeName || maintenType ){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询工装夹具类型列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询工装夹具类型列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询工装夹具类型总数", `select count(*) as count from tm_tool_type ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询工装夹具类型总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询工装夹具类型列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询工装夹具类型列表成功", rows: [], total: 0});
            }
        })
    })
})

// 新增工装夹具类型
router.post("/", (req, res)=>{
    console.log("===========新增工装夹具类型接口============");
    // 获取参数
    let {toolTypeCode, toolTypeName, codeFlag, maintenType, maintenPeriod, remark} = req.body;
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取创建时间
    let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断类型编码和类型名称是否重复
    db.query("查询类型编码和类型名称是否重复", `select * from tm_tool_type where tool_type_code = '${toolTypeCode}' or tool_type_name = '${toolTypeName}'`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询类型编码和类型名称是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "类型编码或类型名称已存在"});
            return;
        }
        // 插入数据库
        let sql = `insert into tm_tool_type (tool_type_code, tool_type_name, code_flag, mainten_type, mainten_period, remark, create_by, create_time)
        values 
        ('${toolTypeCode}', '${toolTypeName}', '${codeFlag}', ${maintenType ? "'"+maintenType+"'" : null}, ${maintenPeriod ? "'"+maintenPeriod+"'" : null}, 
        ${remark ? "'"+remark+"'" : null}, '${username}', '${createTime}')`;
        db.query("新增工装夹具类型", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "新增工装夹具类型失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "新增工装夹具类型成功"});
            }else{
                res.send({code: 500, msg: "新增工装夹具类型失败"});
            }
        })
    })
})

// 查询单个工装夹具类型
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个工装夹具类型接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个工装夹具类型", `select * from tm_tool_type where tool_type_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个工装夹具类型失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个工装夹具类型成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个工装夹具类型失败"});
        }
    })
})

// 修改工装夹具类型
router.put("/", (req, res)=>{
    console.log("===========修改工装夹具类型接口============");
    // 获取参数
    let { toolTypeCode, toolTypeName, codeFlag, maintenType, maintenPeriod, remark, toolTypeId } = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询工装夹具类型名称是否重复
    db.query("查询类型名称是否重复", `select * from tm_tool_type where tool_type_id != ${toolTypeId} and ( tool_type_code = '${toolTypeCode}' or tool_type_name = '${toolTypeName}' )`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询类型名称是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "类型编码或类型名称已存在", data: []});
            return;
        }
        // 修改工装夹具类型sql
        let sql = `update tm_tool_type set tool_type_code = '${toolTypeCode}', tool_type_name = '${toolTypeName}', 
        mainten_type = ${maintenType ? "'"+maintenType+"'" : null}, code_flag = '${codeFlag}', remark=${remark ? "'"+remark+"'" : null}, 
        update_by = '${username}', update_time = '${updateTime}', mainten_period = ${maintenPeriod ? "'"+maintenPeriod+"'" : null}
        where tool_type_id = ${toolTypeId}`;
        db.query("修改工装夹具类型", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改工装夹具类型失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改工装夹具类型成功", data: []});
            }else{
                res.send({code: 500, msg: "修改工装夹具类型失败", data: []});
            }
        })
    })
})

// 删除工装夹具类型
router.delete("/:id", (req, res) => {
    console.log("===========删除工装夹具类型接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from tm_tool_type where tool_type_id in(${id})`;
    // 查询数据库
    db.query("删除工装夹具类型", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除工装夹具类型失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除工装夹具类型成功"})
        }else{
            res.send({code: 500, msg: "删除工装夹具类型失败"})
        }
    })
})

// 查询所有工装夹具类型
router.get("/listAll", (req, res) => {
    console.log("===========查询所有工装夹具类型接口============");

    let sql = `select * from tm_tool_type `;
    // 查询数据库
    db.query("查询所有工装夹具类型", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "查询所有工装夹具类型失败", data: err});
            return
        }
        if (result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
               return toCamelCase(item)
           })
       }
       res.send({code: 200, msg: "查询所有工装夹具类型成功", data: result})
    })
})


module.exports = router;
